package cc.telecomdigital.tdstock.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.ActivityGroup_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.ProgressView;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.IH_UserClient_HttpRequest_Report;
import cc.telecomdigital.tdstock.Services.LS_UserClient.CONNECTION_STATUS;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_ConnectionListener;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;

/**
 * BMP Mode BaseActivity
 * 
 * @author ouyangzhihui
 */
public abstract class BMPBaseActivity extends ActivityGroup_Framework implements ILS_UserClient_ConnectionListener, IH_UserClient_HttpRequest_Report
{
	static final private String				TAG				= BMPBaseActivity.class.getSimpleName();

	protected Handler						_messageHandler	= new Handler();
	protected WindowManager.LayoutParams	mWindowParams;
	protected static WindowManager			mWindowManager;
	protected static Display				_display;
	protected static ViewGroup				_iconTip;
	protected ViewGroup						_iconContent;
//	protected SunFlowerView2				sunFlowerView2;
	protected static SharedPreferences		_prefs;

	@Override
	protected void onCreate(Bundle iSaveInstance)
	{
		super.onCreate(iSaveInstance);
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onCreate");
		
		_display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		
		_prefs = getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
		
		progressView = new ProgressView(GetShowDialogContext());
	}

	@Override
	protected void onResume()
	{
		/*HttpSuperClass*/
		TDStockLog.d(TAG, "onResume: screen lock " + appHost.screenIsLocked);
		
		iHConnectIsDestory = false;
		
		super.onResume();
		
		if(isExectuHttpReqestOnResume)
			SendHttpRequest();
		/*HttpSuperClass*/
		
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onResume");
		
		if(this.getParent() != null)
		{
			BaseActivity._currActivityClass = this.getClass();
		}
		
		/*if(!appHost.LSClient_IsConnected())
		{
//			appHost.LSClient_Connect();
			TryToLogon(false);
		}*/
	}

	@Override
	protected void onPause()
	{
		/*HttpSuperClass*/
		progressView.DismissProgressAll();
		iHConnectIsDestory = true;
		/*HttpSuperClass*/
		
		super.onPause();
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onPause");
	}

	@Override
	protected void onStart()
	{
		super.onStart();
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onStart");
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onRestart");
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onStop");
	}

	@Override
	protected void onDestroy()
	{
		/*HttpSuperClass*/
		progressView.DismissProgressAllOnDestory();
		iHConnectIsDestory = true;
		/*HttpSuperClass*/
		
		super.onDestroy();
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onDestroy");
	}

	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onBackPressed");
		
		StockGroup.forceToGoToRelatingTab();
	}
	
	public static final int		EXIT_APP					= Menu.FIRST + 1;
	public static final int		CREATE_LAUNCHER				= Menu.FIRST;
	public static final String	ACTION_INSTALL_SHORTCUT		= "com.android.launcher.action.INSTALL_SHORTCUT";
	public static final String	EXTRA_SHORTCUT_DUPLICATE	= "duplicate";
	public String				_menu_exit_app_res			= null;
	public String				_menu_gen_launcher_res		= null;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		if (_menu_exit_app_res == null) _menu_exit_app_res = getResources().getString(R.string.app_exit);
		if (_menu_gen_launcher_res == null) _menu_gen_launcher_res = getResources().getString(R.string.app_launcher);

		menu.add(0, CREATE_LAUNCHER, 0, _menu_gen_launcher_res);
		MenuItem mItem = menu.findItem(CREATE_LAUNCHER);
		mItem.setIcon(R.drawable.back_down);
		menu.add(0, EXIT_APP, 1, _menu_exit_app_res);
		mItem = menu.findItem(EXIT_APP);
		mItem.setIcon(R.drawable.down_24_1);

		try
		{
			CustomizeDialog.dismissAll();
		}
		catch (Exception e)
		{
			// e.printStackTrace();
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext()).setExitApp(true);
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int iFeature, MenuItem iItem)
	{
		switch (iItem.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext()).setExitApp(true);
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return true;
	}
	
	protected synchronized void genLauncher()
	{
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.addCategory(Intent.CATEGORY_LAUNCHER);

		intent2.setComponent(new ComponentName(this.getPackageName(), ".activity.SplashActivity"));
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
		sendBroadcast(shortcutIntent);
	}
	
	protected synchronized void exitApp()
	{	
		try
		{
			((ITDLApplication) getApplicationContext()).setExitApp(true);
			appHost.LSClient_Disconnect();
			CustomizeDialog.dismissAll();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		this.finish();
		Process.sendSignal(Process.myPid(), Process.SIGNAL_QUIT);
	}
	
	protected Context getMyOwnContext()
	{
		return getParent() == null ? getApplicationContext() : getParent();
	}
	
	/** modify by zor(ouyangzhihui) -start */
	public void startAnimat(String text)
	{
		mWindowManager = (WindowManager) BMPBaseActivity.this.getMyOwnContext().getSystemService(Context.WINDOW_SERVICE);

		setBitmapImageDesc(text);
		setBitmapImage(text);
	}

	protected WindowManager.LayoutParams getParams()
	{
		final WindowManager.LayoutParams wl = new WindowManager.LayoutParams();

		wl.x = 0;
		wl.y = 0;

		wl.height = WindowManager.LayoutParams.WRAP_CONTENT;
		wl.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wl.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
		wl.format = PixelFormat.TRANSLUCENT;
		wl.windowAnimations = 0;
		return wl;
	}

	private void setBitmapImage(String itemCode)
	{
		try
		{
			if (itemCode.indexOf(" ") != -1)
			{
				itemCode = itemCode.substring(itemCode.indexOf(" ") + 1,
						itemCode.length());
			}
			String text = itemCode.length() >= 5 ? itemCode.substring(0, 5)
					: itemCode;
			if (_iconTip == null)
			{
				_iconTip = (ViewGroup) LayoutInflater.from(this).inflate(
						R.layout.label_tip_icon, null);
			}
			TextView iv = (TextView) _iconTip.findViewById(R.id.tip_code);
			iv.setText(text);
			if (text.length() == 1)
			{
				iv.setBackgroundResource(R.drawable.monitor_cicle);
			}
			else
			{
				iv.setBackgroundResource(R.drawable.monitor_rectangle);
			}

			final WindowManager.LayoutParams wl = getParams();

			int width = _display.getWidth();
			int height = _display.getHeight();
			int iw = iv.getWidth();
			int ih = iv.getHeight();
			int w = (width / 2) / 5 / 2;
			int h = (height / 2) / 8 / 2;

			int wc = w / 2 - iw / 2;
			int hc = h / 2 - ih / 2;

			wl.x = -(width / 20) * 3 + wc;
			wl.y = height / 2 - height / 16 - hc + 3;

			mWindowManager.addView(_iconTip, wl);

		}
		catch (Exception e)
		{
		}
	}

	private void setBitmapImageDesc(String itemCode)
	{
		try
		{
			if (_iconContent == null)
			{
				_iconContent = (ViewGroup) LayoutInflater.from(this)
						.inflate(R.layout.label_tip_content, null);
			}
			TextView iv = (TextView) _iconContent.findViewById(R.id.tip_code);
			iv.setText(itemCode);

			final WindowManager.LayoutParams wl = getParams();
			wl.gravity = Gravity.TOP;
			wl.alpha = 0.3f;
			wl.x = -(_display.getWidth() / 2 - iv.getWidth() / 2 - 10);
			wl.y = 80;

			mWindowManager.addView(_iconContent, wl);

			final Runnable runnable = new Runnable()
			{
				public void run()
				{
					try
					{
						wl.y += 80;
						if (_iconContent != null
								&& mWindowManager != null)
							mWindowManager.updateViewLayout(
									_iconContent, wl);
					}
					catch (Exception e)
					{
					}
				}
			};

			new Thread()
			{
				long	lastUpdate	= System.currentTimeMillis();

				public void run()
				{
					while (wl.y < _display.getHeight() - 60)
					{
						if (System.currentTimeMillis() - lastUpdate >= 100)
						{
							lastUpdate = System.currentTimeMillis();
							_messageHandler.post(runnable);
						}
					}
					if (_iconContent != null && mWindowManager != null)
						mWindowManager.removeView(_iconContent);
				}
			}.start();
		}
		catch (Exception e)
		{
		}
	}

	/** modify by zor(ouyangzhihui) -end */

	@Override
	protected ActivityGroupController GetActivityGroupController()
	{
		return null;
	}

	/*
	 * 跳到足球界面
	 */
//	protected void forwardToSoccerActivity()
//	{
//		TDStockLog.d(TAG, "forwardToSoccerActivity");
//		if(!((ITDLApplication) getApplicationContext()).getIsSoccer())
//		{
//			new CustomizeDialog(this.getParent(), "", appHost.GetLSClient_SportMessag().equals("")?getResources().getString(R.string.realtime_info_msg):appHost.GetLSClient_SportMessag(), getResources().getString(R.string.ok)).show();
//		}
//		else
//		{
//			Intent it = new Intent(this, MainTabActivity.class);
//			it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			SwitchActivityFromHost(MainTabActivity.class, it);
//		}
//	}

	/*
	 * 跳到赛马界面
	 */
//	protected void forwardToHorseraceActivity()
//	{
//		TDStockLog.d(TAG, "forwardToHorseraceActivity");
//		if(!((ITDLApplication) getApplicationContext()).getIsHorse())
//		{
//			new CustomizeDialog(this.getParent(), "", appHost.GetLSClient_HorseMessage().equals("")?getResources().getString(R.string.realtime_info_msg):appHost.GetLSClient_HorseMessage(), getResources().getString(R.string.ok)).show();
//		}
//		else
//		{
//			Intent it = new Intent(this, cc.telecomdigital.tdstock.horserace.activity.MainActivity.class);
//			it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			SwitchActivityFromHost(cc.telecomdigital.tdstock.horserace.activity.MainActivity.class, it);
//		}
//	}

	protected void  handleAnotherLogonAppear() 
	{
		AccountLoginActivity._isAnotherLogonClientAppear = true;   //notify the activity there's another logon.
		
		Intent forwardToLogonActivity = new Intent(this.getApplicationContext(), AccountLoginActivity.class);
		forwardToLogonActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		SwitchActivityFromHost(AccountLoginActivity.class, forwardToLogonActivity);
	}

	protected PopupWindow	netStatusPopupView		= null;
	protected View			netViewObj				= null;
	protected Runnable		netPopupWindow_runnable	= null;

	protected void showDisconnectMessage()
	{

		if (netStatusPopupView == null)
		{
			LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			netViewObj = inflatObj.inflate(R.layout.prompt_network_disconn_pop, null);

			netViewObj.findViewById(R.id.prompt_networking_discon_tips).setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View arg0)
					{
						if (LS_ResumeAllItem() == true)
							hideDisconnectMessage();
					}
				});
			netStatusPopupView = new PopupWindow(netViewObj, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			netStatusPopupView.setAnimationStyle(R.anim.zoom_enter);
			netStatusPopupView.setOutsideTouchable(true);
		}

		if (!netStatusPopupView.isShowing())
		{
			if (netPopupWindow_runnable == null)
			{
				netPopupWindow_runnable = new Runnable()
					{
						public void run()
						{
							netStatusPopupView.showAtLocation(netViewObj, Gravity.BOTTOM | Gravity.RIGHT, 0, 45);
							// _isShowingStreamerTimeoutLabel = true;
						};
					};
			}
			if (_messageHandler == null)
			{
				_messageHandler = new Handler();
			}
			_messageHandler.postDelayed(netPopupWindow_runnable, 300);
		}
	}

	protected void hideDisconnectMessage()
	{
		if (_messageHandler == null)
		{
			_messageHandler = new Handler();
		}
		// _isShowingStreamerTimeoutLabel = false;
		if (netStatusPopupView == null)
			return;

		if (netPopupWindow_runnable != null)
			_messageHandler.removeCallbacks(netPopupWindow_runnable);

		if (netStatusPopupView.isShowing())
			netStatusPopupView.dismiss();
	}
	
	@Override
	public void LS_UserClient_ConnectionReport(CONNECTION_STATUS iStatus)
	{
		TDStockLog.d(TAG, iStatus.name());
		
		if(iStatus == CONNECTION_STATUS.CLOSE_BY_FORCE ) 
		{
			handleAnotherLogonAppear();
			return;
		}
	}

	/**-----------HttpSuperClass---------------*/
	
	protected ProgressView progressView;

	private boolean isExectuHttpReqestOnResume = true;
	protected void SetExectuHttpRequestOnResume(boolean iExecute)
	{
		isExectuHttpReqestOnResume = iExecute;
	}

	protected void ShowMessageDialog(String msgContent)
	{
		CustomizeDialog promptBox;
		promptBox = new CustomizeDialog(GetShowDialogContext(), "提示", msgContent)
		{
			@Override
			public void onClick(View v)
			{
				dismissAll();
			}
		};
//		promptBox.setCancleButton(false);
		promptBox.setCancelable(true);
		promptBox.show();
	}

	protected Context GetShowDialogContext()
	{
		return this.getParent() == null ? this : this.getParent();
	}

	protected void SendHttpRequest()
	{
		if(appHost.screenIsLocked)
			return;
		
		TDStockLog.d(TAG, "SendHttpRequest=>screen lock " + appHost.screenIsLocked);
		
		ShowHideDialog(GetDataFromHttpServer());
	}
	
	protected abstract H_CODE GetDataFromHttpServer();
	
	//show/hide sunflower/progressdalog
	protected boolean iShowProgressView = true;
	
	protected void SetShowProgressView(boolean iShowProgress)
	{
		iShowProgressView = iShowProgress; 
	}
	
	protected void ShowHideDialog(H_CODE statusCode)
	{
		if(statusCode == null)
			return;
		
		if(statusCode == H_CODE.NONE) 
			return;
		
		if (statusCode == H_CODE.OK || statusCode == H_CODE.SYSTEM_BUSY)
		{
			if(iShowProgressView) 
				progressView.ShowProgress();
		}
		else 
		{
			ShowMessageDialog(statusCode.ToString());
		}
	}
	
	protected boolean iHConnectIsDestory = false;
	
	@Override
	public void H_UserClient_HttpRequest_Response(H_UserClient_HttpRequest_Result iResult)
	{
		if(iShowProgressView)
			progressView.DismissProgress();
		
		if(iHConnectIsDestory)
			return;
		
		H_UserClient_HttpRequest_Response_Sub(iResult);
	}
	
	protected abstract void H_UserClient_HttpRequest_Response_Sub(H_UserClient_HttpRequest_Result iResult);
	
}
